﻿#include "DlgMain.h"
#include <QApplication>

#include "Windows.h"
#include "../include/itlogger.h"
#include "../include/itframework.h"
QLibrary    *g_pLoadLogger = NULL;
QLibrary    *g_pLoadFrame = NULL;
ITLogger    *g_pLogger = NULL;
ITFramework *g_pFramework = NULL;

//load Logger.dll
bool Init()
{
    QString strLoggerpath = QString("module/Logger.dll");
    g_pLoadLogger = new QLibrary(strLoggerpath);
    if(g_pLoadLogger->load())
    {
        typedef ITLogger* (*GetInstance)();
        GetInstance pGetInstance = (GetInstance)g_pLoadLogger->resolve("GetInstance");
        if(pGetInstance)
        {
            g_pLogger = pGetInstance();
            if(T_OK == g_pLogger->Init())
            {
                strLoggerpath = ("module/tFramework.dll");
                g_pLoadFrame = new QLibrary(strLoggerpath);
                if(g_pLoadFrame->load())
                {
                    typedef ITFramework* (*GetInstance)();
                    GetInstance pGetInstance = (GetInstance)g_pLoadFrame->resolve("GetInstance");
                    if (pGetInstance)
                    {
                        g_pFramework = pGetInstance();
                        g_pLogger->SetFramework(g_pFramework);
                        g_pFramework->SetLogger(g_pLogger);
                        if(T_OK == g_pFramework->Init())
                        {
                            return true;
                        }
                        else
                        {
                            g_pLogger->WriteLog("Tm Load other dll fail!");
                        }
                    }
                }
            }
            else
                qDebug() << "Tami Load Logger fail!";
        }
    }
    return false;
}

void Exit()
{
    if(NULL != g_pFramework && NULL != g_pLoadFrame)
    {
        g_pFramework->UnInit();
        if(g_pLoadFrame->isLoaded())
        {
            g_pLoadFrame->unload();
            SAFE_DELETE(g_pLoadFrame);
            qDebug() << "Tami unload Framework";
        }
        g_pFramework = NULL;
    }
    if(NULL != g_pLogger && NULL != g_pLoadLogger)
    {
        g_pLogger->UnInit();
        if (g_pLoadLogger->isLoaded())
        {
            g_pLoadLogger->unload();
            SAFE_DELETE(g_pLoadLogger);
            qDebug() << "Tami unload Logger";
        }
        g_pLogger = NULL;
    }
}

bool checkMutex()
{
    HANDLE hMutex = CreateMutex(NULL, FALSE,  L"TmV1MUI");
    if (ERROR_ALREADY_EXISTS == GetLastError())
    {
        CloseHandle(hMutex);
        hMutex  =  NULL;
        return  false;
    }
    else
        return true;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    if(!checkMutex())
        return 0;

    if(!Init())
        return 0;

    DlgMain w;
    w.show();

    a.exec();
    Exit();

    qDebug() << "Tami main end!";
    return 0;
}
